<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'姓名'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
    </div>
    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <!--<el-table-column :label="'序号'" fixed prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'姓名'" fixed align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'性别'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'推荐岗位'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一面评价纬度" align="center">
        <el-table-column :label="'工作动力(20)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_gzdl }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'专业技能(20)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_zyjn }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'项目经验(20)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_xmjy }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'学习创新(20)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_xxcx }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'执行落实(20)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_zxls }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'总分(100)'" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.first_total }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="二面评价纬度" align="center">
        <el-table-column :label="'职业素养(25)'" align="center" prop="reviewer">
          <template slot-scope="scope">
            <span>{{ scope.row.second_zysy }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'专业能力(25)'" align="center" prop="reviewer">
          <template slot-scope="scope">
            <span>{{ scope.row.second_zynl }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'工作思路(25)'" align="center" prop="reviewer">
          <template slot-scope="scope">
            <span>{{ scope.row.second_gzsl }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'沟通协作(25)'" align="center" prop="reviewer">
          <template slot-scope="scope">
            <span>{{ scope.row.second_gtxz }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="'总分(100)'" align="center" prop="reviewer">
          <template slot-scope="scope">
            <span>{{ scope.row.second_total }}</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList"/>
    <el-dialog :visible.sync="dialogFormVisible" title="HR终面-OFFER评价" @close="resetHrdialogForm">
      <el-row>
        <div class="z-center">
          <el-button type="info" plain>姓名： {{ dialogForm.basic.name }}</el-button>
        </div>
        <div class="z-center">
          <el-button type="info" plain>性别： {{ dialogForm.basic.sex_name }}</el-button>
        </div>
        <div class="z-center">
          <el-button type="info" plain>推荐岗位： {{ dialogForm.basic.recommend }}</el-button>
        </div>
        <div class="z-center">
          <el-button type="info" plain>面试批次： {{ dialogForm.basic.batch }}</el-button>
        </div>
      </el-row>
      <div style="height: 20px;"></div>
      <el-alert :closable="false" title="HR终面评价维度" type="info" center></el-alert>
      <div style="height: 25px;"></div>

      <el-form ref="hrDialogForm" :rules="rules" :model="hrDialogForm" label-width="100px">
        <el-form-item label="接受offer" prop="delivery">
          <el-switch v-model="hrDialogForm.send_offer"></el-switch>
        </el-form-item>
        <transition name="fade-transform" mode="out-in">
          <el-form-item v-if="!hrDialogForm.send_offer" label="拒绝原因" prop="delivery">
            <el-input v-model="hrDialogForm.reject_offer_reason" type="textarea" rows="4"></el-input>
          </el-form-item>
        </transition>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="createData">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPv, updateArticle } from '@/api/article'
import { getOfferSuccessList, lastHrCComment } from '@/api/interview'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'OfferSuccess',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      totalCount: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      queryString: '',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        status: [
          { required: true, message: '请选择合适选项', trigger: 'change' }
        ],
        boss: [
          { required: true, message: '请输入面试官名称', trigger: 'blur' }
        ],
        is_system_in: [
          { required: true, message: '请选择合适选项', trigger: 'change' }
        ],
        system_in_level: [
          { required: true, message: '请选择合适选项', trigger: 'change' }
        ],
        recommend_level: [
          { required: true, message: '请选择合适选项', trigger: 'change' }
        ],
        ability: [
          { required: true, message: '请选择合适选项', trigger: 'change' }
        ]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      dialogForm: {
        id: undefined,
        t1: 0,
        t2: 0,
        t3: 0,
        t4: 0,
        t5: 0,
        total: 0,
        comment: '',
        status: 5,
        boss: '',
        basic: {
          name: '',
          sex_name: '',
          recommend: '',
          batch: ''
        }
      },
      hrDialogForm: {
        id: undefined,
        send_offer: true,
        reject_offer_reason: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange() {
      this.totalCount = this.num1 + this.num2 + this.num3 + this.num4 + this.num5
    },
    editTable(row) {
      this.dialogFormVisible = true
      this.hrDialogForm.id = row.id
      this.dialogForm.basic.name = row.name
      this.dialogForm.basic.sex_name = row.sex_name
      this.dialogForm.basic.batch = row.batch
      this.dialogForm.basic.recommend = row.recommend
    },
    getList() {
      this.listLoading = true
      getOfferSuccessList(this.listQuery.page, this.queryString).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      if (name) {
        query += `name=${name}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      lastHrCComment(this.hrDialogForm).then(response => {
        this.dialogFormVisible = false
        this.getList()
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      })
    },
    resetHrdialogForm() {
      this.hrDialogForm = {
        id: undefined,
        tan_xin_status: true,
        tan_xin: 0,
        tan_xin_a: 'k',
        tan_xin_b: '月',
        tan_xin_reason: '',
        tijian: true,
        tijian_reason: '',
        send_offer: true,
        reject_offer_reason: ''
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    jifen2() {
      this.secondDialogForm.total = this.secondDialogForm.t1 +
        this.secondDialogForm.t2 + this.secondDialogForm.t3 + this.secondDialogForm.t4
    }
  }
}
</script>

<style scoped>
  .z-center {
    text-align: left;
    margin: 8px 0 8px 0;
  }
</style>
